package com.xnf.ssmweb.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.xnf.ssmweb.domain.Role;
import com.xnf.ssmweb.domain.UserInfo;
import com.xnf.ssmweb.service.RoleService;
import com.xnf.ssmweb.service.UserInfoService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chendx on 2021/3/30.
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/toUserInfo")
    @RolesAllowed("ROLE_ROOT")
    public ModelAndView toUserInfo(){
        ModelAndView mav = new ModelAndView();
        List<UserInfo> userInfos = userInfoService.queryUserInfos();
        mav.addObject("userInfos",userInfos);
        mav.setViewName("/user-list");
        return mav;
    }

    @RequestMapping("/toUserInfoById")
    public ModelAndView toUserInfoById(Long id){
        ModelAndView mav = new ModelAndView();
        UserInfo userInfo = userInfoService.queryUserById(id);
        mav.addObject("userInfo",userInfo);
        mav.setViewName("/user-show");
        return mav;
    }

    @RequestMapping("/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) Long userId){
        ModelAndView mav = new ModelAndView();
        List<Role> roles = roleService.findNoRoleList(userId);
        mav.addObject("roles",roles);
        mav.addObject("id",userId);
        mav.setViewName("/user-role-add");
        return mav;
    }

    @RequestMapping("/saveUserInfo")
    public ModelAndView saveUserInfo(UserInfo userInfo){
        ModelAndView mav = new ModelAndView();
        boolean flag = userInfoService.saveUserInfo(userInfo);
        if (flag) mav.setViewName("redirect:/userInfo/toUserInfo");
        else mav.setViewName("/user-add");
        return mav;
    }

    @RequestMapping("/addRoleToUser")
    public ModelAndView addRoleToUser(@RequestParam(name = "ids" , required =true ) String[] roleIds, Long userId){
        ModelAndView mav = new ModelAndView();
        boolean flag = userInfoService.addRoleToUser(roleIds,userId);
        if (flag) mav.setViewName("redirect:/userInfo/toUserInfoById?id="+userId);
        else mav.setViewName("redirect:/userInfo/findUserByIdAndAllRole?id="+userId);
        return mav;
    }

}
